package com.woniu.interceptor;

import com.woniu.annotation.RequirePermission;
import com.woniu.annotation.RequireRole;
import com.woniu.server.RedisKey;
import com.woniu.server.RedisUtil;
import com.woniu.utils.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Component
public class PermissionInterceptor implements HandlerInterceptor {
    @Resource
    private RedisUtil redisUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if("OPTIONS".equals(request.getMethod())){
            return true;
        }
        //取出当前登录用户的角色
        String token = request.getHeader("token");
        if (token == null) {
            return true;
        }
        String role = JwtUtil.parseToken(token).get("roleName").toString();
        Integer userId = null;
        if(role.equals("管理员")||role.equals("超级管理员")){
            userId = Integer.parseInt(JwtUtil.parseToken(token).get("adminId").toString());
        }else if(role.equals("学生")||role.equals("商家")||role.equals("维修员")){
            userId = Integer.parseInt(JwtUtil.parseToken(token).get("userId").toString());
        }

        //获取请求将要执行的控制层方法
        HandlerMethod h = (HandlerMethod) handler;
        Method method = h.getMethod();
        //获取当前控制层方法的权限注解
        boolean required = method.isAnnotationPresent(RequireRole.class);
        if(required){
            String[] value = method.getAnnotation(RequireRole.class).value();
            if(Arrays.asList(value).contains(role)){
                //角色符合
                if(method.isAnnotationPresent(RequirePermission.class)){
                    String requirePermission = method.getAnnotation(RequirePermission.class).value();
                    //取出redis中存储的用户权限列表
                    Set<String> set = new HashSet<>();
                    if(role.equals("管理员")||role.equals("超级管理员")){
                        set = redisUtil.smembers(RedisKey.adminPermission(userId));
                    }else if(role.equals("学生")||role.equals("商家")||role.equals("维修员")){
                        set = redisUtil.smembers(RedisKey.userPermission(userId));
                    }
                    if(set.contains(requirePermission)){
                        return true;
                    }else {
                        throw new Exception("权限不足");
                    }
                }else {
                    return true;
                }
            }else{
                throw new Exception("权限不足");
            }
        }
        return true;
    }
}
